package 
{
	import flash.geom.Rectangle;

	public final class collisionmanager
	{
		public static const BUNKY:uint = 0;
		public static const TINKU:uint = 1;
		public static const FRIENDLY_FIRE:uint = 2;
		public static const REWARD:uint = 3;
		
		private static var _collidables:Array;						/*BUNKY*/	/*TINKU*/	/*F.FIRE*/	/*REWARD*/
		private static const _collideMap:Array = [	/*BUNKY*/	[	false,		true,		false,		true],
													/*TINKU*/	[	true, 		false, 		true,		false],
													/*F.FIRE*/	[	false, 		true, 		false,		false],	
													/*REWARD*/	[	true,		false,		false,		false]	]; 
		
		public static function addCollidable(obj:ICollidable):void
		{
			if(_collidables == null)
				_collidables = new Array();
			
			_collidables.push(obj);
		}
		
		public static function removeCollidable(obj:ICollidable):void
		{			
			_collidables.splice(_collidables.indexOf(obj), 1);
		}

		public static function updateCollision():void
		{
			if(_collidables == null) return;
			
			var length:uint = _collidables.length;
			trace("Active Collidables: " + length);
			for(var i:uint = 0; i <length-1; ++i)
			{
				var obj1:ICollidable = _collidables[i];
				if(obj1 == null) continue;
				for(var j:uint = i+1; j <length; ++j)
				{
					var obj2:ICollidable = _collidables[j];		
					if(obj2 ==null) continue;
					if(	obj1.visible && obj2.visible && 					
						_collideMap[obj1.collisionID][obj2.collisionID] )
					{
						var tObj1:ICollidable;
						var tObj2:ICollidable;
						
						if(obj1 is tinku || obj1 is Collectable)
						{
							tObj1 = obj1;
							tObj2 = obj2;
						}
						else if(obj2 is tinku || obj2 is Collectable)
						{
							tObj1 = obj2;
							tObj2 = obj1;
						}
							
						var rec1:Rectangle = tObj1.bounds.clone();
						
						//only enemy objects need to be transformed into
						//camera space before collision tests. Bullets and 
						//hero-character are already in camera space at this
						//point.
						rec1.x -= tObj1.camera.getCameraPosX();						
						rec1.y -= tObj1.camera.getCameraPosY();
 
						if(rec1.intersects(tObj2.bounds))
						{
							obj1.onColliding(obj2);
							obj2.onColliding(obj1);
						}						
					}
				}				
			}
		}
	}	
}